package org.dromara.common.websocket.config

import org.dromara.common.websocket.config.properties.WebSocketProperties
import org.dromara.common.websocket.handler.PlusWebSocketHandler
import org.dromara.common.websocket.interceptor.PlusWebSocketInterceptor
import org.dromara.common.websocket.listener.WebSocketTopicListener
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.web.socket.WebSocketHandler
import org.springframework.web.socket.config.annotation.EnableWebSocket
import org.springframework.web.socket.config.annotation.WebSocketConfigurer
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry
import org.springframework.web.socket.server.HandshakeInterceptor

/**
 * WebSocket 配置
 *
 * @author LikeYouDo
 * @date 2025/09/22
 */
@AutoConfiguration
@ConditionalOnProperty(value = ["websocket.enabled"], havingValue = "true")
@EnableConfigurationProperties(WebSocketProperties::class)
@EnableWebSocket
class WebSocketConfig {
    @Bean
    fun webSocketConfigurer(
        handshakeInterceptor: HandshakeInterceptor,
        webSocketHandler: WebSocketHandler, webSocketProperties: WebSocketProperties
    ): WebSocketConfigurer {
        // 如果WebSocket的路径为空，则设置默认路径为 "/websocket"
        if (webSocketProperties.path.isBlank()) {
            webSocketProperties.path = "/websocket"
        }

        // 如果允许跨域访问的地址为空，则设置为 "*"，表示允许所有来源的跨域请求
        if (webSocketProperties.allowedOrigins.isBlank()) {
            webSocketProperties.allowedOrigins = "*"
        }

        // 返回一个WebSocketConfigurer对象，用于配置WebSocket
        return WebSocketConfigurer { registry: WebSocketHandlerRegistry ->
            // 添加WebSocket处理程序和拦截器到指定路径，设置允许的跨域来源
            registry
                .addHandler(webSocketHandler, webSocketProperties.path)
                .addInterceptors(handshakeInterceptor)
                .setAllowedOrigins(webSocketProperties.allowedOrigins)
        }
    }

    @Bean
    fun handshakeInterceptor(): HandshakeInterceptor = PlusWebSocketInterceptor()

    @Bean
    fun webSocketHandler(): WebSocketHandler = PlusWebSocketHandler()

    @Bean
    fun topicListener(): WebSocketTopicListener = WebSocketTopicListener()

}
